package com.qiantu.phone.ui.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Parcel;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.hjq.base.BaseActivity;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.swipelayout.SimpleSwipeListener;
import com.hjq.widget.swipelayout.SwipeLayout;
import com.hjq.widget.swipelayout.adapters.RecyclerSwipeAdapter;
import com.hjq.widget.view.SwitchButton;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.ThemeUtil;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.event.RefreshSceneIntentEvent;
import com.qiantu.phone.event.UpdateFavouriteEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.AddTaskActivity;
import com.qiantu.phone.ui.activity.EditSceneBaseActivity;
import com.qiantu.phone.ui.activity.LinkageStartStopActivity;
import com.qiantu.phone.ui.activity.PushMessageSettingActivity;
import com.qiantu.phone.ui.activity.SceneIconSelectActivity;
import com.qiantu.phone.ui.activity.SceneIntentListActivity;
import com.qiantu.phone.ui.activity.SceneInterruptModeActivity;
import com.qiantu.phone.ui.activity.ScenePrivateActivity;
import com.qiantu.phone.ui.activity.SelectFloorRoomActivity;
import com.qiantu.phone.ui.activity.SwitchBindActivity;
import com.qiantu.phone.ui.dialog.BottomDelayTimeDialog;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.OptionDialog;
import com.qiantu.phone.ui.dialog.SceneTaskSortDialog;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.utils.TempDataHolder;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SceneDetailBaseAdapter extends RecyclerSwipeAdapter {

    //不要修改，需要根据position
    protected int TOP_VIEW_TYPE = 0;
    protected int EMPTY_SCENE_VIEW_TYPE = 1;
    protected int TASK_VIEW_TYPE = 2;
    protected int DELETE_VIEW_TYPE = 3;
    protected int TASK_POSITION_OFFSET = 2;
    protected SceneDetailBean mSceneDetailBean;
    protected EditSceneBaseActivity mEditSceneActivity;
    private int firstTaskItemMarginTop;
    private int lastTaskItemWhiteCoverMarginBottom;
    private int lastTaskItemContentMarginBottom;
    private String selectRoomSerialNo;
    protected boolean hasDelete = true;

    public String targetSerialNo;

    public SceneDetailBaseAdapter(EditSceneBaseActivity activity, SceneDetailBean mSceneDetailBean){
        mEditSceneActivity = activity;
        this.mSceneDetailBean = mSceneDetailBean;
        firstTaskItemMarginTop = mEditSceneActivity.getResources().getDimensionPixelSize(R.dimen.dp_m_12);
        lastTaskItemWhiteCoverMarginBottom = mEditSceneActivity.getResources().getDimensionPixelSize(R.dimen.dp_12);
        lastTaskItemContentMarginBottom = mEditSceneActivity.getResources().getDimensionPixelSize(R.dimen.dp_4);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = null;
        if(viewType == EMPTY_SCENE_VIEW_TYPE){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_empty_task, parent, false);
            return new EmptyTaskItemViewHolder(view);
        } else {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.scene_task_item, parent, false);
            return new TaskItemViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if(viewHolder instanceof EmptyTaskItemViewHolder){
            //更新是否有添加提示
            if (mSceneDetailBean.getSceneTasks().size()>0){
                ((EmptyTaskItemViewHolder) viewHolder).vTip.setVisibility(View.GONE);
            }else {
                ((EmptyTaskItemViewHolder) viewHolder).vTip.setVisibility(View.VISIBLE);
            }
        }else if (viewHolder instanceof TaskItemViewHolder) {
            position = position - TASK_POSITION_OFFSET;
            RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams) viewHolder.itemView.getLayoutParams();
            FrameLayout.LayoutParams whiteCoverLayoutLayoutParams = (FrameLayout.LayoutParams) ((TaskItemViewHolder) viewHolder).whiteCoverLayout.getLayoutParams();
            FrameLayout.LayoutParams swipeLayoutLayoutParams = (FrameLayout.LayoutParams) ((TaskItemViewHolder) viewHolder).swipeLayout.getLayoutParams();
            if(position == 0 && position == mSceneDetailBean.getSceneTasks().size() - 1){
                rl.topMargin = firstTaskItemMarginTop;
                whiteCoverLayoutLayoutParams.bottomMargin = lastTaskItemWhiteCoverMarginBottom;
                swipeLayoutLayoutParams.bottomMargin = lastTaskItemContentMarginBottom;
            }else if(position == 0){
                rl.topMargin = firstTaskItemMarginTop;
                whiteCoverLayoutLayoutParams.bottomMargin = 0;
                swipeLayoutLayoutParams.bottomMargin = 0;
            }else if(position == mSceneDetailBean.getSceneTasks().size() - 1){
                rl.topMargin = 0;
                whiteCoverLayoutLayoutParams.bottomMargin = lastTaskItemWhiteCoverMarginBottom;
                swipeLayoutLayoutParams.bottomMargin = lastTaskItemContentMarginBottom;
            }else{
                rl.topMargin = 0;
                whiteCoverLayoutLayoutParams.bottomMargin = 0;
                swipeLayoutLayoutParams.bottomMargin = 0;
            }
            TaskItemViewHolder vh = (TaskItemViewHolder) viewHolder;
            vh.ly.setTag(position);
            vh.sortTextView.setTag(position);
            vh.deleteImage.setTag(position);
            vh.copyImage.setTag(position);
            vh.addImage.setTag(position);
            vh.delayTime.setTag(position);
            SceneDetailBean.SceneTaskBean sceneTaskBean = mSceneDetailBean.getSceneTasks().get(position);
            if (sceneTaskBean.getSceneTaskType() == 1) {
                if(sceneTaskBean.getSceneDeviceInstruct() != null){
                    SceneDetailBean.SceneDeviceInstructBean bean = sceneTaskBean.getSceneDeviceInstruct();
                    setDeviceViewData(vh,bean.getDeviceItemSerialNo(),bean.getDeviceItemStateData().getStatus(),sceneTaskBean,bean.getTriggerTime());
                }else{
                    vh.valuesLy.setVisibility(View.GONE);
                    vh.name.setText(sceneTaskBean.getName());
                    GlideApp.with(AppApplication.getInstance())
                            .load(BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + sceneTaskBean.getImage() + "_on.png")
                            .into(vh.icon);
                }
                vh.delayTime.setVisibility(View.VISIBLE);
                if(targetSerialNo != null && targetSerialNo.equals(sceneTaskBean.getSceneDeviceInstruct().getDeviceItemSerialNo())){
                    vh.whiteCoverLayout.setSelected(true);
                }else{
                    vh.whiteCoverLayout.setSelected(false);
                }
            }else if(sceneTaskBean.getSceneTaskType() == 5){
                if(sceneTaskBean.getSceneDeviceGroupInstruct() != null){
                    SceneDetailBean.SceneDeviceGroupInstruct bean = sceneTaskBean.getSceneDeviceGroupInstruct();
                    setDeviceViewData(vh,bean.getDeviceGroupSerialNo(),bean.getStateData().getStatus(),sceneTaskBean,bean.getTriggerTime());
                }else{
                    vh.valuesLy.setVisibility(View.GONE);
                    vh.name.setText(sceneTaskBean.getName());
                    GlideApp.with(AppApplication.getInstance())
                            .load(BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + sceneTaskBean.getImage() + "_on.png")
                            .into(vh.icon);
                }
                vh.delayTime.setVisibility(View.VISIBLE);
                if(targetSerialNo != null && targetSerialNo.equals(sceneTaskBean.getSceneDeviceGroupInstruct().getDeviceGroupSerialNo())){
                    vh.whiteCoverLayout.setSelected(true);
                }else{
                    vh.whiteCoverLayout.setSelected(false);
                }
            }else {
                vh.icon.setImageDrawable(LLSceneLinkageUtil.getTaskIcon(sceneTaskBean.getSceneTaskType()));
                vh.value.setVisibility(View.VISIBLE);
                vh.valuesLy.setVisibility(View.GONE);
                vh.delayTime.setVisibility(View.GONE);
                StringBuilder stringBuilder = new StringBuilder();
                for (String s : LLSceneLinkageUtil.makeTaskBriefing(sceneTaskBean)) {
                    stringBuilder.append(s).append(",");
                }
                vh.value.setText(stringBuilder.substring(0, stringBuilder.length() - 1));
                vh.name.setText(sceneTaskBean.getName());
            }
            vh.swipeLayout.addSwipeListener(new SimpleSwipeListener() {
                @Override
                public void onOpen(SwipeLayout layout) {
                    viewHolder.setIsRecyclable(false);
                }

                @Override
                public void onClose(SwipeLayout layout) {
                    viewHolder.setIsRecyclable(true);
                }
            });
            mItemManger.bind(viewHolder.itemView, position);//实现只展现一条列表项的侧滑区域
            vh.sortTextView.setText(String.valueOf(position + 1));
        }
    }

    @Override
    public int getItemCount() {
        int taskCount;
        if (mSceneDetailBean == null || mSceneDetailBean.getSceneTasks() == null) {
            taskCount = 0;
        } else {
            taskCount = mSceneDetailBean.getSceneTasks().size();
        }
        int deleteCount;
        if (!hasDelete || mSceneDetailBean == null || TextUtils.isEmpty(mSceneDetailBean.getSceneSerialNo())) {
            deleteCount = 0;
        } else {
            deleteCount = 1;
        }
        return TASK_POSITION_OFFSET + taskCount + deleteCount;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TOP_VIEW_TYPE;
        } else if(position == 1){
            return EMPTY_SCENE_VIEW_TYPE;
        } else if (hasDelete && position == getItemCount() - 1 && mSceneDetailBean != null && !TextUtils.isEmpty(mSceneDetailBean.getSceneSerialNo())) {
            return DELETE_VIEW_TYPE;
        } else {
            return TASK_VIEW_TYPE;
        }
    }

    private void setDeviceViewData(TaskItemViewHolder vh,String deviceSerialNo,Map<String, String> status,SceneDetailBean.SceneTaskBean sceneTaskBean,int trigger){
        vh.value.setVisibility(View.GONE);
        vh.valuesLy.setVisibility(View.VISIBLE);
        DeviceBean device = LLDeviceDBManager.getInstance(AppApplication.getInstance()).get(deviceSerialNo);
        if (device != null) {
            GlideApp.with(AppApplication.getInstance())
                    .load(device.getOnImageUrl())
                    .placeholder(vh.icon.getDrawable())
                    .into(vh.icon);
            String deviceType = null;
            String type = null;
            if (device != null) {
                type = device.getType();
                deviceType = device.getDeviceType();
            }
            List<String> values = new ArrayList<>();
            if (device.getDeviceType().equals(DeviceType.UNIVERSAL_SEQUENCER.stringType) || device.getDeviceType().equals(DeviceType.UNIVERSAL_PROJECTOR.stringType) || device.getDeviceType().equals(DeviceType.UNIVERSAL_PLAYER.stringType) || device.getDeviceType().equals(DeviceType.UNIVERSAL_PA.stringType) || device.getDeviceType().equals("universal_freshair")){
                List<UniversalDeviceData> datas = LLDeviceActionDBManager.getInstance(AppApplication.getInstance()).getDeviceDatasByDeviceSerialNo(device.getDeviceSerialNo());
                Set<String> keys = status.keySet();
                for(String key : keys){
                    for(UniversalDeviceData data : datas){
                        if(key.equals(data.getActionIdentifier())){
                            if(data.getIsEnum()){
                                if(data.getRangeIdentifier().equals(status.get(key))){
                                    if(device.getDeviceType().equals("universal_sequencer")){
                                        values.add(String.format("%s:%s",data.getCombineName(),data.getRangeName()));
                                    }else{
                                        values.add(data.getRangeName());
                                    }
                                    break;
                                }
                            }else{
                                values.add(String.format("%s℃",status.get(key)));
                                break;
                            }
                        }
                    }
                }
            }else{
                values = LLDeviceUtil.getValueStr_max3(type, deviceType, status, deviceSerialNo);
            }
            vh.delayTime.setVisibility(View.VISIBLE);
            if(trigger == 0){
                vh.delayTime.setText("立即执行");
            }else{
                String time = String.format("%02d:%02d后执行",trigger/1000/60,trigger/1000%60);
                vh.delayTime.setText(time);
            }
            if (values.size() == 0) {
                vh.value1.setVisibility(View.GONE);
                vh.value2.setVisibility(View.GONE);
                vh.value3.setVisibility(View.GONE);
            } else if (values.size() == 1) {
                vh.value1.setVisibility(View.VISIBLE);
                vh.value1.setText(values.get(0));
                vh.value2.setVisibility(View.GONE);
                vh.value3.setVisibility(View.GONE);
            } else if (values.size() == 2) {
                vh.value1.setVisibility(View.VISIBLE);
                vh.value1.setText(values.get(0));
                vh.value2.setVisibility(View.VISIBLE);
                vh.value2.setText(values.get(1));
                vh.value3.setVisibility(View.GONE);
            } else {
                vh.value1.setVisibility(View.VISIBLE);
                vh.value1.setText(values.get(0));
                vh.value2.setVisibility(View.VISIBLE);
                vh.value2.setText(values.get(1));
                vh.value3.setVisibility(View.VISIBLE);
                vh.value3.setText(values.get(2));
            }
            vh.value2.setVisibility(View.GONE);
            vh.value3.setVisibility(View.GONE);
            vh.name.setText(device.getName());
        }else{
            vh.valuesLy.setVisibility(View.GONE);
            vh.name.setText(sceneTaskBean.getName());
            GlideApp.with(AppApplication.getInstance())
                    .load(BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix()  + sceneTaskBean.getImage() + "_on.png")
                    .into(vh.icon);
        }
    }

    public Map<String,Integer> getSceneTaskData(){
        Map<String,Integer> map = new HashMap<>();
        for(SceneDetailBean.SceneTaskBean taskBean : mSceneDetailBean.getSceneTasks()){
            if(taskBean.getSceneTaskType() == 1 || taskBean.getSceneTaskType() == 5){
                String taskSerialNo;
                if(taskBean.getSceneTaskType() == 1){
                    taskSerialNo = taskBean.getSceneDeviceInstruct().getDeviceItemSerialNo();
                }else{
                    taskSerialNo = taskBean.getSceneDeviceGroupInstruct().getDeviceGroupSerialNo();
                }
                if(map.get(taskSerialNo) != null){
                    map.put(taskSerialNo,map.get(taskSerialNo) + 1);
                }else{
                    map.put(taskSerialNo,1);
                }
            }
        }
        return map;
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe_layout;
    }

    private final View.OnClickListener taskListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            if (v.getId() == R.id.add_image) {
                Intent intent = new Intent(v.getContext(), AddTaskActivity.class);
                intent.putExtra("position", position);
                intent.putExtra("type", AddTaskActivity.TYPE_SCENE);
                intent.putExtra("sceneType", mSceneDetailBean.getSceneType());
                intent.putExtra("taskData", (Serializable) getSceneTaskData());
                v.getContext().startActivity(intent);
                mItemManger.closeItem(position);
            }else if(v.getId() == R.id.copy_image){
                SceneDetailBean.SceneTaskBean taskBean = mSceneDetailBean.getSceneTasks().get(position);
                Gson gson = new Gson();
                String json = gson.toJson(taskBean);
                SceneDetailBean.SceneTaskBean newBean = gson.fromJson(json,SceneDetailBean.SceneTaskBean.class);
                newBean.setSceneTaskSerialNo("");
                mSceneDetailBean.getSceneTasks().add(position,newBean);
                notifyDatasetChanged();
                mItemManger.closeItem(position);
            }else if (v.getId() == R.id.delete_image) {
                showDeleteHintDialog(position);
            }else if(v.getId() == R.id.sort_image){
                showBottomSceneTaskSortDialog(position);
            }else if (v.getId() == R.id.ly) {
                if (mItemManger.isOpen(position)) {
                    mItemManger.closeItem(position);
                } else {
                    editTask(position);
                }
            }else if (v.getId() == R.id.delay_time) {
                showBottomTimeDialog(position);
            }
        }
    };

    private class EmptyTaskItemViewHolder extends RecyclerView.ViewHolder {
        private ImageView addTask;
        private View vTip;

        public EmptyTaskItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            addTask = itemView.findViewById(R.id.add_task);
            vTip = itemView.findViewById(R.id.tip);

            addTask.setOnClickListener(topBottomViewOnClickListener);
            vTip.setOnClickListener(topBottomViewOnClickListener);
        }
    }

    private class TaskItemViewHolder extends RecyclerView.ViewHolder {

        public View whiteCoverLayout;
        public SwipeLayout swipeLayout;
        public LinearLayout seeLayout;
        public ImageView copyImage;
        public ImageView addImage;
        public TextView sortTextView;
        public ImageView deleteImage;
        public ImageView icon;
        public TextView name;
        public TextView delayTime;
        public TextView value;
        public TextView value1;
        public TextView value2;
        public TextView value3;
        public LinearLayout valuesLy;
        public View ly;

        public TaskItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            whiteCoverLayout = itemView.findViewById(R.id.white_cover_layout);
            swipeLayout = itemView.findViewById(R.id.swipe_layout);
            seeLayout = itemView.findViewById(R.id.see_layout);
            sortTextView = itemView.findViewById(R.id.sort_image);
            copyImage = itemView.findViewById(R.id.copy_image);
            addImage = itemView.findViewById(R.id.add_image);
            deleteImage = itemView.findViewById(R.id.delete_image);
            icon = itemView.findViewById(R.id.icon);
            name = itemView.findViewById(R.id.name);
            delayTime = itemView.findViewById(R.id.delay_time);
            value = itemView.findViewById(R.id.value);
            value1 = itemView.findViewById(R.id.value1);
            value2 = itemView.findViewById(R.id.value2);
            value3 = itemView.findViewById(R.id.value3);
            valuesLy = itemView.findViewById(R.id.status_ly);
            ly = itemView.findViewById(R.id.ly);

            ly.setOnClickListener(taskListener);
            delayTime.setOnClickListener(taskListener);
            sortTextView.setOnClickListener(taskListener);
            deleteImage.setOnClickListener(taskListener);
            copyImage.setOnClickListener(taskListener);
            addImage.setOnClickListener(taskListener);
        }
    }

    protected class DeleteItemViewHolder extends RecyclerView.ViewHolder {
        public TextView btnDelete;

        public DeleteItemViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            btnDelete = itemView.findViewById(R.id.btn_delete);
            btnDelete.setOnClickListener(topBottomViewOnClickListener);
        }
    }

    protected View.OnClickListener topBottomViewOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = null;
            switch (view.getId()) {
                case R.id.set_name:
                    showBottomEditDialog(((SettingBar)view).getRightText().toString().trim());
                    break;
                case R.id.select_icon:
                case R.id.scene_icon:
                    intent = new Intent(mEditSceneActivity, SceneIconSelectActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    intent.putExtra("selectIcon", mSceneDetailBean.getImage());
                    intent.putExtra("sceneType", mSceneDetailBean.getSceneType());
                    mEditSceneActivity.startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, @Nullable Intent data) {
                            if (resultCode == Activity.RESULT_OK) {
                                String selectIconUrl = data.getStringExtra("DATA");
                                mSceneDetailBean.setImage(selectIconUrl);
                                notifyItemChanged(0, "updateIcon");
                                mEditSceneActivity.checkRightClick();
                            }
                        }
                    });
                    break;
                case R.id.select_room:
                    intent = new Intent(mEditSceneActivity, SelectFloorRoomActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    if(mSceneDetailBean.getLinkType() == 3){
                        intent.putExtra("roomSerialNo", mSceneDetailBean.getFloorSerialNo());
                        intent.putExtra("linkType", mSceneDetailBean.getLinkType());
                    }else{
                        intent.putExtra("roomSerialNo", mSceneDetailBean.getRoomSerialNo());
                        intent.putExtra("linkType", mSceneDetailBean.getLinkType());
                    }
                    intent.putExtra("title", mEditSceneActivity.getString(R.string.affiliation_room));
                    mEditSceneActivity.startActivityForResult(intent, new BaseActivity.OnActivityCallback() {
                        @Override
                        public void onActivityResult(int resultCode, @Nullable Intent data) {
                            if (resultCode == Activity.RESULT_OK) {
                                selectRoomSerialNo = data.getStringExtra("serialNo");
                                String floorSerialNo = data.getStringExtra("floorSerialNo");
                                String floorName  = data.getStringExtra("floorName");
                                if(floorSerialNo != null && floorSerialNo.equals(selectRoomSerialNo)){
                                    mSceneDetailBean.setLinkType(3);
                                    mSceneDetailBean.setRoomSerialNo("");
                                    mSceneDetailBean.setRoomName("");
                                    mSceneDetailBean.setFloorSerialNo(floorSerialNo);
                                    mSceneDetailBean.setFloorName(floorName);
                                }else{
                                    if (RoomBean.ROOM_COMMON_SERIALNO.equals(selectRoomSerialNo)) {
                                        mSceneDetailBean.setLinkType(2);
                                    } else {
                                        mSceneDetailBean.setLinkType(1);
                                    }
                                    mSceneDetailBean.setRoomSerialNo(selectRoomSerialNo);
                                    String floorRoomName = LLRoomDBManager.getInstance(mEditSceneActivity).getFloorRoomName(selectRoomSerialNo);
                                    mSceneDetailBean.setRoomName(floorRoomName);
                                }
                                mSceneDetailBean.setFloorSerialNo(floorSerialNo);
                                mSceneDetailBean.setFloorName(floorName);
                                notifyItemChanged(0, "updateRoom");
                                mEditSceneActivity.checkRightClick();
                            }
                        }
                    });
                    break;
                case R.id.frequently_switch:
                    mSceneDetailBean.setFavourite(((SwitchButton)view).isChecked());
                    mEditSceneActivity.checkRightClick();
                    break;
                case R.id.add_sort:

                    break;
                case R.id.add_task:
                case R.id.tip:
                    intent = new Intent(mEditSceneActivity, AddTaskActivity.class);
                    intent.putExtra("type", AddTaskActivity.TYPE_SCENE);
                    intent.putExtra("sceneType", mSceneDetailBean.getSceneType());

                    intent.putExtra("taskData", (Serializable) getSceneTaskData());
                    mEditSceneActivity.startActivity(intent);
                    break;
                case R.id.btn_delete:
                    mEditSceneActivity.showConfirmCancelHintDialog(mEditSceneActivity.getString(R.string.delete_scene_hint),
                            mEditSceneActivity.getString(R.string.cancel),
                            mEditSceneActivity.getString(R.string.delete_text),
                            new ConfirmCancelHintDialog.OnListener() {
                                @Override
                                public void onLeftClick(BaseDialog dialog) {
                                    dialog.dismiss();
                                }

                                @Override
                                public void onRightClick(BaseDialog dialog) {
                                    dialog.dismiss();
                                    List<String> sceneSerialNoList = new ArrayList<>();
                                    sceneSerialNoList.add(mSceneDetailBean.getSceneSerialNo());
                                    LLHttpManager.deleteScene(mEditSceneActivity, sceneSerialNoList, new HttpCallback<HttpData<Boolean>>(null) {
                                        @Override
                                        public void onSucceed(HttpData<Boolean> result) {
                                            super.onSucceed(result);
                                            LLSceneDBManager.getInstance(mEditSceneActivity).remove(mSceneDetailBean.getSceneSerialNo());
                                            switch (mSceneDetailBean.getSceneType()){
                                                case 1:
                                                    EventBus.getDefault().post(new RefreshSceneEvent(mSceneDetailBean.getRoomSerialNo(), mSceneDetailBean.getFavourite()));
                                                    if(mSceneDetailBean.getFavourite() != null && mSceneDetailBean.getFavourite()){
                                                        EventBus.getDefault().post(new UpdateFavouriteEvent(UpdateFavouriteEvent.TYPE_ADD));
                                                    }
                                                    break;
                                                case 3:
                                                    EventBus.getDefault().post(new RefreshSceneIntentEvent());
                                                    break;
                                            }
                                            TempDataHolder.clearEditSceneDetailBean(mSceneDetailBean.getSceneType());
                                            mEditSceneActivity.finish();
                                        }
                                    });
                                }
                            });
                    break;
                case R.id.interrupt_mode:
                    intent = new Intent(mEditSceneActivity, SceneInterruptModeActivity.class);
                    intent.putExtra("sceneSerialNo", mSceneDetailBean.getSceneSerialNo());
                    mEditSceneActivity.startActivity(intent);
                    break;
                case R.id.btn_scene_condition_setting_more:
                    if(!TextUtils.isEmpty(mSceneDetailBean.getSceneSerialNo())){
                        showOptionDialog(view);
                    }
                    break;
            }
        }
    };

    BottomEditDialog mBottomEditDialog;
    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(mEditSceneActivity);
            mBottomEditDialog.setMaxLength(8);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    mSceneDetailBean.setName(mBottomEditDialog.getText());
                    notifyItemChanged(0, "updateName");
                    mEditSceneActivity.checkRightClick();
                }
            });
            new XPopup.Builder(mEditSceneActivity)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        if(mSceneDetailBean.getSceneType() == 3){
            mBottomEditDialog.setLabel(mEditSceneActivity.getString(R.string.scene_intent_name));
            mBottomEditDialog.setHint(mEditSceneActivity.getString(R.string.please_enter_scene_intent_name));
        }else{
            mBottomEditDialog.setLabel(mEditSceneActivity.getString(R.string.scene_name));
            mBottomEditDialog.setHint(mEditSceneActivity.getString(R.string.please_enter_scene_name));
        }
        mBottomEditDialog.setMaxLength(Constants.SCENE_NAME_MAX_LENGTH);
        mBottomEditDialog.setText(text);
        mBottomEditDialog.show();
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;
    private void showDeleteHintDialog(int position) {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(mEditSceneActivity);
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                mSceneDetailBean.getSceneTasks().remove(position);
                //notifyItemRemoved(position);
                notifyDataSetChanged();
                mItemManger.closeAllItems();
                mEditSceneActivity.checkRightClick();
            }
        });
        mConfirmCancelHintDialogBuilder.setContent(mEditSceneActivity.getString(R.string.delete_task_hint));
        mConfirmCancelHintDialog.show();
    }


    private SceneTaskSortDialog mSceneTaskSortDialog;
    private void showBottomSceneTaskSortDialog(int position){
        if (mSceneTaskSortDialog == null) {
            mSceneTaskSortDialog = new SceneTaskSortDialog(mEditSceneActivity);
            new XPopup.Builder(mEditSceneActivity)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mSceneTaskSortDialog);
        }
        SceneDetailBean.SceneTaskBean taskBean = mSceneDetailBean.getSceneTasks().get(position);
        mSceneTaskSortDialog.setDialogClickListener(new SceneTaskSortDialog.DialogClickListener() {
            @Override
            public void onConfirmClick(int index) {
                mSceneTaskSortDialog.dismiss();
                mSceneDetailBean.getSceneTasks().remove(position);
                mSceneDetailBean.getSceneTasks().add(index,taskBean);
                notifyDataSetChanged();
                mItemManger.closeAllItems();
                mEditSceneActivity.checkRightClick();
            }
        });
        int time = 0;
        if(taskBean.getSceneTaskType() == 1){
            time = taskBean.getSceneDeviceInstruct().getTriggerTime();
        }else if(taskBean.getSceneTaskType() == 5){
            time = taskBean.getSceneDeviceGroupInstruct().getTriggerTime();
        }
        int beginIndex = 0,endIndex = 0;
        boolean isBegin = false;
        boolean isEnd = false;
        for(int i = 0;i < mSceneDetailBean.getSceneTasks().size();i++){
            SceneDetailBean.SceneTaskBean bean = mSceneDetailBean.getSceneTasks().get(i);
            int sortTime = 0;
            if(bean.getSceneTaskType() == 1){
                sortTime = bean.getSceneDeviceInstruct().getTriggerTime();
            }else if(bean.getSceneTaskType() == 5){
                sortTime = bean.getSceneDeviceGroupInstruct().getTriggerTime();
            }
            if(sortTime == time && !isBegin){
                isBegin = true;
                beginIndex = i;
            }
            if(isBegin && sortTime != time){
                endIndex = i - 1;
                isEnd = true;
                break;
            }
        }
        if(isBegin && !isEnd){
            endIndex = mSceneDetailBean.getSceneTasks().size() - 1;
        }
        mSceneTaskSortDialog.setData(position,beginIndex+1,endIndex+1);
        mSceneTaskSortDialog.setLabel("滑动设定该设备在此场景/联动中的序号");
        mSceneTaskSortDialog.show();
    }


    private void editTask(int position) {
        SceneDetailBean.SceneTaskBean sceneTaskBean = mSceneDetailBean.getSceneTasks().get(position);
        switch (sceneTaskBean.getSceneTaskType()){
            case 1:{//设备指令
                mEditSceneActivity.showDeviceDialog(sceneTaskBean, position + TASK_POSITION_OFFSET);
                break;
            }
            case 2:{//延时任务
//                mEditSceneActivity.showBottomTimeDialog(sceneTaskBean, position + TASK_POSITION_OFFSET);
                break;
            }
            case 3:{
                Intent intent = new Intent(mEditSceneActivity, PushMessageSettingActivity.class);
                intent.putExtra("serial_no", sceneTaskBean.getSceneTaskSerialNo());
                intent.putExtra("type", AddTaskActivity.TYPE_SCENE);
                intent.putExtra("sceneType", mSceneDetailBean.getSceneType());
                mEditSceneActivity.startActivity(intent);
                break;
            }
            case 4:{
                Intent intent = new Intent(mEditSceneActivity, LinkageStartStopActivity.class);
                intent.putExtra("serial_no", sceneTaskBean.getSceneTaskSerialNo());
                intent.putExtra("type", AddTaskActivity.TYPE_SCENE);
                intent.putExtra("sceneType", mSceneDetailBean.getSceneType());
                mEditSceneActivity.startActivity(intent);
                break;
            }
            case 5:{//设备指令
                mEditSceneActivity.showGroupDialog(sceneTaskBean, position + TASK_POSITION_OFFSET);
                break;
            }
        }
    }

    private OptionDialog optionDialog;

    private void showOptionDialog(View atView) {
        if (optionDialog == null) {
            List<OptionDialog.Option> options = new ArrayList<>();
            options.add(new OptionDialog.Option(R.attr.icon_intelligent_switchbind, mEditSceneActivity.getString(R.string.switch_binding)));
            options.add(new OptionDialog.Option(R.attr.icon_intelligent_intent, mEditSceneActivity.getString(R.string.scene_intent)));
            options.add(new OptionDialog.Option(R.attr.icon_intelligent_privatescene, mEditSceneActivity.getString(R.string.private_scene)));
            optionDialog = new OptionDialog(mEditSceneActivity)
                    .setOptions(options).setListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                            optionDialog.dismiss();
                            Intent intent = null;
                            switch (position) {
                                case 0:
                                    SwitchBindActivity.startForScene(mEditSceneActivity, mSceneDetailBean.getSceneSerialNo(), mSceneDetailBean.getHouseSerialNo(), mSceneDetailBean.getSceneType(), new BaseActivity.OnActivityCallback() {
                                        @Override
                                        public void onActivityResult(int resultCode, @Nullable Intent data) {
                                            if (resultCode == Activity.RESULT_OK) {
                                                notifyItemChanged(0, "updateBindStatus");
                                            }
                                        }
                                    });
                                    break;
                                case 1:
                                    intent = new Intent(mEditSceneActivity, SceneIntentListActivity.class);
                                    intent.putExtra("sceneSerialNo", mSceneDetailBean.getSceneSerialNo());
                                    mEditSceneActivity.startActivity(intent);
                                    break;
                                case 2:
                                    intent = new Intent(mEditSceneActivity, ScenePrivateActivity.class);
                                    intent.putExtra("sceneSerialNo", mSceneDetailBean.getSceneSerialNo());
                                    mEditSceneActivity.startActivity(intent);
                                    break;
                            }
                        }
                    });
            new XPopup.Builder(mEditSceneActivity)
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(mEditSceneActivity.getResources().getDimensionPixelSize(R.dimen.dp_10))
                    .offsetY(-mEditSceneActivity.getResources().getDimensionPixelSize(R.dimen.dp_4))
                    .asCustom(optionDialog);
        }
        optionDialog.show();
    }

    private BottomDelayTimeDialog mBottomDelayTimeDialog;
    public void showBottomTimeDialog(int position){

        if (mBottomDelayTimeDialog == null) {
            mBottomDelayTimeDialog = new BottomDelayTimeDialog(mEditSceneActivity);
            new XPopup.Builder(mEditSceneActivity)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomDelayTimeDialog);
        }
        SceneDetailBean.SceneTaskBean sceneTaskBean = mSceneDetailBean.getSceneTasks().get(position);
        mBottomDelayTimeDialog.setDialogClickListener(new BottomDelayTimeDialog.DialogClickListener() {
            @Override
            public void onConfirmClick(String time, int longTime) {
                mBottomDelayTimeDialog.dismiss();
                updateTime(sceneTaskBean,longTime);
            }
        });
        if(sceneTaskBean.getSceneTaskType() == 1){
            mBottomDelayTimeDialog.setMillisecond(sceneTaskBean.getSceneDeviceInstruct().getTriggerTime());
        }else{
            mBottomDelayTimeDialog.setMillisecond(sceneTaskBean.getSceneDeviceGroupInstruct().getTriggerTime());
        }
        mBottomDelayTimeDialog.show();
    }

    private void updateTime(SceneDetailBean.SceneTaskBean sceneTaskBean,int longTime){
        if(sceneTaskBean.getSceneTaskType() == 1){
            sceneTaskBean.getSceneDeviceInstruct().setTriggerTime(longTime);
        }else{
             sceneTaskBean.getSceneDeviceGroupInstruct().setTriggerTime(longTime);
        }
        mSceneDetailBean.getSceneTasks().sort(new Comparator<SceneDetailBean.SceneTaskBean>(){
            @Override
            public int compare(SceneDetailBean.SceneTaskBean o1, SceneDetailBean.SceneTaskBean o2) {
                int time1 = 0;
                int time2 = 0;
                if(o1.getSceneTaskType() == 1){
                    time1 = o1.getSceneDeviceInstruct().getTriggerTime();
                }else if(o1.getSceneTaskType() == 5){
                    time1 = o1.getSceneDeviceGroupInstruct().getTriggerTime();
                }
                if(o2.getSceneTaskType() == 1){
                    time2 = o2.getSceneDeviceInstruct().getTriggerTime();
                }else if(o2.getSceneTaskType() == 5){
                    time2 = o2.getSceneDeviceGroupInstruct().getTriggerTime();
                }
                if(time1 == time2){
                    if(o1.getSort() == null){
                        return 1;
                    }
                    if(o2.getSort() == null){
                        return -1;
                    }
                    return o1.getSort() - o2.getSort();
                }
                return time1 - time2;
            }
        });

        notifyDataSetChanged();
    }
}
